(function(){
    angular.module('app').filter('toTrusted', ['$sce', function($sce) {
        return function(text) {
            return $sce.trustAsHtml(text);
        };
    }]).controller("agOrderCtrl",function($scope,proxy,$stateParams,$state){
        $scope.searchActive = "";
        $scope.dataType = [0, "	品牌名称/贊助信息", "描述信息", "用户评级", "点赞数", "下载数量",
            "价格", "售卖价格", "服务电话", "地址", "描述信息2", "URL", "评论数", "H5"];
        $scope.adTypes = [0, "banner", "开屏", "插屏", "视频贴片", "原生", "激励视频"];
        $scope.interactionTypes = [0, "仅展示", "下载应用", 0 ,"跳转网页"];
        $scope.permission = PERMISSION;
        $scope.hasActiveId = !!$stateParams.activeId;

        $scope.newOrder = function () {
            var bidOrder = PERMISSION.act["订单"].sub["新建竞价订单"],
                dealOrder = PERMISSION.act["订单"].sub["新建合约订单"];
            if(bidOrder && !dealOrder) {
                $state.go('agent.delivery.newOrder',{oType: '1', orderId: '','activeId':''})
            } else if (!bidOrder && dealOrder) {
                $state.go('agent.delivery.newOrder',{oType: '2', orderId: '','activeId':'0'})
            } else {
                localStorage.step = 1;
                layer.open({
                    type: 1,
                    title: "新建广告订单",
                    skin: "layer-style",
                    area: ['660px', '380px'], //宽高
                    content: $(".orderType")
                });
            }
        };
        //停用创意
        $scope.delCreative = function (orderId, cId, pIndex, index) {
            deleteCreative($scope, proxy, orderId, cId, pIndex, index);
        };

        $scope.clearLayer = function () {
            layer.closeAll();
        };
        //复制订单
        $scope.copyOrder = {
            creative: true,
            pop: function (item, e) {
                //停止冒泡
                e.stopPropagation()
                layer.open({
                    type: 1,
                    title: "复制订单",
                    skin: "layer-style",
                    area: ['460px', '200px'], //宽高
                    content: $('.copy-order-box')
                })
                this.name = item.name;
                this.item = item;
            },
            copy: function () {
                proxy.proxy({
                    url: STATIC_URL.domian+'/dsp/order/clone',
                    data: {
                        data: {
                            orderID: this.item.id,
                            cloneCreative: $scope.copyOrder.creative + '',
                            activityID: this.item.activityID,
                            orderName: $scope.copyOrder.name == this.item.name ? undefined : $scope.copyOrder.name
                        }
                    },
                    success: function(res){
                        if (res.status == '0') {
                            layer.closeAll()
                            layer.msg("复制订单成功。")
                            getList()
                        }
                    }
                })
            }
        }
        // 全选状态
        $scope.allCheck = false;
        $scope.activeIDs = [];
        $scope.obj={
            'sTime':getNowFormatDate()+' '+'00:00:00', //默认今日
            'eTime':getNowFormatDate()+' '+'23:59:59',
            'filter':{activityID:$stateParams.activeId},
        };
        $scope.checks = ["1"];
        $scope.radios = 2;
       // 全部，待投放，投放中，结束，暂停
        $scope.typeList = [
            {
                id:undefined,
                name:"全部"
            },
            {
                id:'pdb,pd',
                name:"合约交易"
            },
            {
                id:'rtb',
                name:"竞价交易"
            },
        ];
        $scope.searchVal = "";

        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/activity/list',
            data:{
                'size': '-1',
                "sort": ["cTime,1"],
            },
            load:true,
            success: function(res){
                // 获得列表
                $scope.activeList = res.data.data;               
                //$scope.activeList.unshift({name:"全部"})
                // 默认查询
                if($scope.hasActiveId) {
                    $scope.activeList.forEach(function(v){
                        if(v.activityID == $stateParams.activeId) {
                            $scope.searchActive = v.name
                        }
                    })
                }
            }
        });
        
        //过滤-----竞价类型
        $scope.typeCall = function(item){
            $scope.obj.filter.orderType= item.id;
            getList()
        };
        //过滤-----订单状态
        $scope.statusCall = function(item){
            $scope.obj.filter.orderState = item.id;
            getList()
        };
        //显示订单下面的素材
        $scope.showSpace = function(item, $event){
            item.showFlag = !item.showFlag;
            if(item.showFlag){
                proxy.proxy({
                    url: STATIC_URL.domian+'/dsp/order/creative/list',
                    data: {
                        "orderID": item.id
                    },
                    load: true,
                    success: function (res) {
                        if(res.data.length!=0){
                            item.materialList = res.data || [];
                            item.materialList.forEach(function (v) {
                                getPreview(v)
                            })
                        }


                    }
                });
            }

        };

        $scope.showImg = function(url) {
            layer.photos({
                photos: {
                    "data": [
                      {
                        "src": url,
                      }
                    ]
                  }
                ,anim: 5
              });
        }
        $scope.showIframe = function(doc) {
            $scope.srcdoc = doc;
            layer.open({
                type: 1,
                shade: 0.3,
                closeBtn: 0,
                shadeClose: true,
                title: false, //不显示标题
                content: $('.iframe-box')
            })
        }
        $scope.showVideo = function(src) {
            var video = $('.video-box video')[0];
            if($scope.videoSrc == src) {
                video.currentTime = 0;
                video.pause();
            } else {
                $scope.videoSrc = src;
            }
            layer.open({
                type: 1,
                shade: 0.3,
                closeBtn: 0,
                shadeClose: true,
                area: ['500px', ''], //宽高
                title: false, //不显示标题
                content: $('.video-box'),
                cancel: function(){
                    video.pause()
                }
            })
        }

        $('.video-box video')[0].oncanplay = function () {
            this.play();
        }
        //诊断订单
        $scope.diagnosis = function (id, $event) {
            $event.stopPropagation();
            $scope.checkTitle = "订单";
            diagnosis($scope, proxy, id, "order");
        };
        //诊断创意
        $scope.checkCrective = function (id, $event) {
            $event.stopPropagation();
            $scope.checkTitle = "创意";
            diagnosis($scope, proxy, id, "creative");
        };
        $scope.statusList =[
            {
                id:undefined,
                name:"全部"
            },
            {
                id:'10',
                name:"待投放"
            },
            {
                id:'20',
                name:"投放中"
            },
            {
                id:'30',
                name:"结束"
            },
            {
                id:'40',
                name:"暂停"
            },
        ];
        //过滤-----归属活动
        $scope.activeCall = function(item){
            $scope.obj.filter.activityID = item.activityID;
            getList();
        }
        $scope.activeUp = function($event,item){
            if(item==''){
                $scope.obj.filter.activityID =undefined;
                getList();
            }
        }
        // 素材全选事件
        $scope.allCheckFunc = function(checked){
            $scope.activeIDs = [];
            if(checked) {
                $(".activeFlag").each(function(){
                    $scope.activeIDs.push($(this).attr("value"));
                })
            }
        };
        // 素材点击事件
        $scope.checkFunc = function() {
            // 素材框全勾选时,勾选全选框
            $scope.allCheck = $scope.activeIDs.length == $(".activeFlag").length;
        };
        //修改订单状态
        $scope.setStatus = function(item,index){
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/order/modify',
                data: {
                    data:{
                        state:item.state=='10'?'20':'10','id':item.id
                    }
                },
                success: function(res){
                    //.state=(item.state=='10'?'20':'10');
                    item.state=(item.state=='10'?'20':'10');
                },
                error: function() {
                    item.open = !item.open;
                }
            })
        };
        //订单列表修改订单
        $scope.nameChange = function(item,key,flag, $event){
            $event.stopPropagation();
            var data = {
                'id':item.id,
                'type':item.type,
            };
            data[key] = item[key];  
            if (data.orderBudget == '') {
                data.orderBudget = '0';
            } else if(isNaN(item.orderBudget) || item.orderBudget < 0) {
                return layer.msg("总预算必须为大于0的数字！")
            }
            if(isNaN(item.bidPrice) || item.bidPrice <= 0) {
                return layer.msg("出价必须为大于0的数字！")
            }
            var max = $scope[item.chargeMode+"Max"];
            if(item.bidPrice > max) {
                return layer.msg("出价不得高于"+max+"元")
            }
            if(key=='frequencyLimit') {
                if (item.freqTemp == '') {
                    item.freqTemp = '0';
                } else if(isNaN(item.freqTemp) || item.freqTemp < 0) {
                    return layer.msg("频次必须为大于0的数字！")
                }
                data.frequencyUnit = item.frequencyUnit;
                data.frequencyLimit = item.freqTemp;
            }   
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/order/modify',
                data: {data:data},
                success: function(res){
                    item[flag] = !item[flag];
                    if(key=='frequencyLimit'){
                        item.frequencyLimit = data.frequencyLimit;
                    }
                }
            })
        }
        //编辑
        $scope.editName = function (item, $event) {
            item.nameFlag = !item.nameFlag;
            $event.stopPropagation();
        };

        $scope.editMoney = function (item, $event) {
            item.orderBudgetFlag = !item.orderBudgetFlag;
            $event.stopPropagation();
        };

        $scope.editPrice = function (item, $event) {
            item.frequencyLimitFlag = !item.frequencyLimitFlag;
            $event.stopPropagation();
        }
        //时间过滤
        $scope.chooseDate = function(sTime,eTime){
            $scope.obj.sTime = sTime+' '+'00:00:00';
            $scope.obj.eTime = eTime+' '+'23:59:59';
            getList();
        };
        //状态过滤
        $scope.chooseStatus = function(item){
            $scope.obj.orderState= item.id;
            getList();
        };

        $scope.isSingleImg = function(item) {
            var m = item.material || [];
            return (m.length == 1 && m[0].image);
        }
        $scope.showAlert = function(i,$event,item) {
            $event.stopPropagation();
            $scope.currentItem = {
                i: i,
                item: item
            }
            if(i.auditState == "2") {
                layer.open({
                    type: 1,
                    title: "操作提示",
                    closeBtn: 1,
                    shadeClose: true,
                    area:["434px"],
                    content: $(".alert-box")
                });
            } else {
                $scope.changeCreative();
            }
        }
        $scope.changeCreative = function () {
            var reg = /^((ht|f)tps?):\/\//;
            var i = $scope.currentItem.i;
            var item = $scope.currentItem.item;
            if(!i.landingUrlTemp) return layer.msg("落地页不能为空。");
            if(!reg.test(i.landingUrlTemp)) return layer.msg("落地页地址不合法。");
            var data = {
                data: {
                    id:i.id,
                    templateID: i.templateID,
                    landingUrl: i.landingUrlTemp
                }
            }
            proxy.proxy({
                url: STATIC_URL.domian+"/dsp/creative/modify",
                data: data,
                load:true,
                success: function(res){
                    layer.closeAll();
                    layer.msg("修改成功。")
                    item.showFlag = false;
                    i.urlFlag = false;
                    $scope.showSpace(item);
                }
            })
        }


        getList();
        getPriceMax();

        function getList(current, pagesize) {
            var data = {
                'page': (current || 1)+"",
                'size': (pagesize || 20)+"",
                'filter':$scope.obj.filter,
                //'sTime' : $scope.obj.sTime,
                //'eTime' : $scope.obj.eTime,
                "sort": ["cTime,1"],
            };
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/order/list',
                data: data,
                load:true,
                success: function(res){
                    // 获得列表
                    $scope.orderList = res.data.data;
                    $("#pageToolbar").html("");
                    $('#pageToolbar').Paging({pagesize: pagesize || '20',current: current || '1',count:res.data.total,toolbar:true,'hash': false,
                        callback:getList});
                }
            })
        };
        // 控制CPC/CPM最高价格
        function getPriceMax() {
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/sys/parameter/query',
                data: {
                    "filter":{"feature":"dsp.feature.advertiser.order.cpc.maxvalue"}
                },
                success: function(res){
                    $scope.cpcMax = res.data[0].value*1 || 99;
                }
            })
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/sys/parameter/query',
                data: {
                    "filter":{"feature":"dsp.feature.advertiser.order.cpm.maxvalue"}
                },
                success: function(res){
                    $scope.cpmMax = res.data[0].value*1 || 999;
                }
            })
        }
    })

    //删除素材
    function deleteCreative(scope, proxy, orderId, cId,pIndex, index) {
        console.log(pIndex, index);
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/order/creative/del',
            data: {
                "orderID": orderId,
                "creativeID": cId
            },
            load: true,
            success: function (res) {
                scope.orderList[pIndex].materialList.splice(index, 1);
            }
        })
    }
    //订单诊断
    function diagnosis(scope, proxy, id, type) {
        var data = {};
        data[type + "ID"] = id;
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/check/order',
            data: data,
            load: true,
            success: function (res) {
                scope.currCheckInfo = res.data;
                scope.currCheckInfo.id = id;
                if (type == "creative") {
                    scope.currCheckInfo = res.data.Creatives[0];
                    scope.currCheckInfo.id = id;
                }
                layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shadeClose: true,
                    area: ['500px'], //宽高
                    content: $(".diagnosis-box")
                });
            }
        })
    }
    function getPreview (item) {
        var m = item.material || [];
        for(var i = 0; i < m.length; i++) {
            var v = m[i];
            if(v.image) {
                item.hasImg = true;
                item.preview = v.image.url;
                break;
            }
            if(v.video) {
                item.hasVideo = true;
                item.preview = v.video.url;
                break;
            }
            if(v.data && v.data.type == "13") {
                item.hasHtml = true;
                item.preview = v.data.content;
                break;
            }
        }
    }

})();

